<template>
  <div class="address-card">
    <h4 class="ad-header">收货人信息</h4>
    <div class="ad-form-container">
      <div class="ad-default-form" v-if="defalutAddress" v-show="!isEdit">
        <span>
          {{ defalutAddress.name }} {{ defalutAddress.phone }}
          {{ defalutAddress.province }} {{ defalutAddress.city }}
          {{ defalutAddress.region }}
        </span>
        <el-button link type="success" @click="isEdit = true">修改</el-button>
      </div>
      <div class="ad-default-form" v-if="!defalutAddress" v-show="!isEdit">
        <el-button color="#1aa684" @click="isEdit = true" size="small"
          >添加新地址</el-button
        >
      </div>
      <div v-show="isEdit == true">
        <div v-if="addressList.length > 0">
          <div v-for="item in addressList" :key="item.id">
            <el-radio v-model="isAddAddress" :label="item.id">
              {{ item.name }} {{ item.phone }} {{ item.province }}
              {{ item.city }}
              {{ item.region }}
            </el-radio>
          </div>
        </div>
        <el-row>
          <el-col :span="14">
            <div class="ad-form-content">
              <el-radio v-model="isAddAddress" label="0">使用新地址</el-radio>
              <el-form
                v-if="isAddAddress == 0"
                class="ad-form"
                ref="addressFormRef"
                :rules="rules"
                :model="addressForm"
                label-width="80px"
              >
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="收货人" prop="name">
                      <el-input
                        placeholder="收件人名称"
                        v-model="addressForm.name"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="邮政编码" prop="postCode">
                      <el-input
                        placeholder="邮政编码"
                        v-model="addressForm.postCode"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="手机号码" prop="phone">
                      <el-input
                        placeholder="请输入真实号码"
                        v-model="addressForm.phone"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="8">
                    <el-form-item label="所在地区" prop="provinceIndex">
                      <el-select
                        v-model="addressForm.provinceIndex"
                        placeholder="省份"
                        @change="filterRegion(0)"
                        clearable
                      >
                        <el-option
                          v-for="(item, index) in RegionalData[0]"
                          :key="item[0]"
                          :label="item[1]"
                          :value="item[0]"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      prop="cityIndex"
                      v-if="addressForm.provinceIndex"
                      label-width="0px"
                    >
                      <el-select
                        v-model="addressForm.cityIndex"
                        placeholder="城市"
                        @change="filterRegion(1)"
                        clearable
                      >
                        <el-option
                          v-for="(item, index) in RegionalData[
                            addressForm.provinceIndex
                          ]"
                          :key="item[0]"
                          :label="item[1]"
                          :value="item[0]"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      prop="regionIndex"
                      label-width="0px"
                      v-if="addressForm.cityIndex"
                    >
                      <el-select
                        v-model="addressForm.regionIndex"
                        placeholder="区/县"
                        clearable
                      >
                        <el-option
                          v-for="(item, index) in RegionalData[
                            addressForm.cityIndex
                          ]"
                          :key="item[0]"
                          :label="item[1]"
                          :value="item[0]"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="详细地址" prop="detailAddress">
                  <el-input
                    type="textarea"
                    placeholder="请填写正式地址"
                    v-model="addressForm.detailAddress"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button @click="submitAddressForm" color="#1aa684"
                    >保存收货人信息</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
        <el-row v-show="isEdit && isAddAddress != 0">
          <el-button color="#1aa684" @click="saveReciverInfo"
            >保存收货人信息</el-button
          >
        </el-row>
      </div>
    </div>
  </div>
</template>
<script setup>
import RegionalData from "@/assets/json/regionalData.json";
import {
  addAddress,
  updateAddress,
  listAddress,
} from "@/api/mall/client/user/address";
import { watch } from "vue";
const isAddAddress = ref("0");
const isEdit = ref(false);
const defalutAddress = ref({});
const { proxy } = getCurrentInstance();
const props = defineProps({
  addressList: {
    type: Array,
    default: () => [],
  },
});
const addressList = ref([]);
const getAddressList = async () => {
  const res = await listAddress();
  addressList.value = res.data;
};
const rules = ref({
  name: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[34578]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  provinceIndex: [{ required: true, message: "请选择省份", trigger: "change" }],
  cityIndex: [{ required: true, message: "请选择城市", trigger: "change" }],
  regionIndex: [{ required: true, message: "请选择区县", trigger: "change" }],
  postCode: [
    { pattern: /^[1-9]\d{5}$/, message: "请输入正确的邮编", trigger: "blur" },
  ],
  detailAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
});
watch(
  () => addressList.value,
  (val) => {
    console.log(val);
    defalutAddress.value = val.find((item) => item.defaultStatus == 1);
    if (defalutAddress.value) {
      isAddAddress.value = defalutAddress.value.id;
    }
  },
  {
    deep: true,
  },
  {
    immediate: true,
  }
);

// 筛选地区
const addressForm = ref({
  name: undefined,
  phone: undefined,
  postCode: undefined,
  province: undefined,
  city: undefined,
  region: undefined,
  detailAddress: undefined,
  provinceIndex: undefined,
  cityIndex: undefined,
  regionIndex: undefined,
});
const filterRegion = (level) => {
  switch (level) {
    case 0:
      delete addressForm.value.cityIndex;
      delete addressForm.value.regionIndex;
      break;
    case 1:
      delete addressForm.value.regionIndex;
      break;
    default:
      break;
  }
};

// 提交表单
const emit = defineEmits(["saveAddressInfo"]);
const addressFormRef = ref();
const submitAddressForm = async () => {
  await addressFormRef.value.validate((valid) => {
    if (valid) {
      // 组装参数
      console.log(RegionalData[addressForm.value.provinceIndex]);
      addressForm.value.province = filterAddress(
        RegionalData[0],
        addressForm.value.provinceIndex
      );
      addressForm.value.city = filterAddress(
        RegionalData[addressForm.value.provinceIndex],
        addressForm.value.cityIndex
      );
      addressForm.value.region = filterAddress(
        RegionalData[addressForm.value.cityIndex],
        addressForm.value.regionIndex
      );
      addressForm.value.defaultStatus = 1;
      if (addressForm.value.id == undefined) {
        addAddress(addressForm.value).then((res) => {
          proxy.$modal.msgSuccess("收货信息保存成功");
          getAddressList().then((res) => {
            const address = listAddress.find((item) => item.defaultStatus == 1);
            // 通知父组件
            emit("saveAddressInfo", address.id);
            isEdit.value = false;
          });
        });
      } else {
        updateAddress(addressForm.value).then((res) => {
          proxy.$modal.msgSuccess("收货信息修改成功");
          getAddressList();
        });
      }
      console.log("提交成功", addressForm.value);
    } else {
      console.log("提交失败");
    }
  });
};

// 保存收货人信息
const saveReciverInfo = () => {
  defalutAddress.value = addressList.value.find(
    (item) => item.id == isAddAddress.value
  );
  emit("saveAddressInfo", isAddAddress.value);
  isEdit.value = false;
};

// 过滤地址
const filterAddress = (item, index) => {
  const address = item.find((e) => e[0] == index);
  return address[1];
};

getAddressList();
</script>

<style lang="scss" scoped>
.el-radio {
  :deep(.el-radio__input.is-checked .el-radio__inner) {
    background: #1aa684 !important;
    border-radius: 50%;
  }
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #1aa684;
  }
}
.address-card {
  background: #f4f4f4;
  padding: 10px 20px;
  margin-top: 10px;
  .ad-header {
    font-size: 20px;
    font-weight: 300;
    padding: 10px 0;
  }
  .ad-default-form {
    .el-button {
      margin-left: 10px;
    }
  }
  .ad-form-content {
    display: flex;

    .ad-form {
      margin-top: 25px;
      flex: 1;
    }
  }
}
</style>
